package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/swsk33/sclog"
	"gitee.com/swsk33/sentinel-fetch/global"
	"gitee.com/swsk33/sentinel-fetch/model"
	"net/http"
)

// 对欧空局OData API的请求封装

// QueryByIdentifierList 根据影像名称列表，批量查询全部详细元数据
func QueryByIdentifierList(identifierList []string) (*model.ODataResponse, error) {
	// 准备请求
	requestBody := model.NewQueryRequest(identifierList)
	bodyByte, e := json.Marshal(requestBody)
	if e != nil {
		sclog.ErrorLine("序列化请求体出错！")
		return nil, e
	}
	// 发起请求
	content, e := global.SendRequest(fmt.Sprintf("%s/OData.CSC.FilterList?$expand=Locations", global.ProductQuery), http.MethodPost, global.JSON, bodyByte)
	if e != nil {
		sclog.ErrorLine("发送请求出错！")
		return nil, e
	}
	// 解析响应
	var result model.ODataResponse
	e = json.Unmarshal(content, &result)
	if e != nil {
		sclog.ErrorLine("反序列化响应体出错！")
		return nil, e
	}
	return &result, nil
}

// LoginAndGetToken 获取访问Token
//
//   - username 用户名
//   - password 密码
func LoginAndGetToken(username, password string) (*model.LoginToken, error) {
	// 准备请求
	bodyString := fmt.Sprintf("grant_type=password&username=%s&password=%s&client_id=cdse-public", username, password)
	// 发起请求
	content, e := global.SendRequest(global.AuthEndpoint, http.MethodPost, global.UrlEncoded, []byte(bodyString))
	if e != nil {
		sclog.ErrorLine("登录并获取Token失败！")
		return nil, e
	}
	// 解析响应
	var result model.LoginToken
	e = json.Unmarshal(content, &result)
	if e != nil {
		sclog.ErrorLine("反序列化响应失败！")
		return nil, e
	}
	if result.AccessToken == "" || result.RefreshToken == "" {
		sclog.ErrorLine(string(content))
		return nil, errors.New("登录失败！")
	}
	return &result, nil
}

// RefreshToken 刷新AccessToken
//
//   - refreshToken 刷新用的Token
func RefreshToken(refreshToken string) (*model.LoginToken, error) {
	// 准备请求
	bodyString := fmt.Sprintf("grant_type=refresh_token&refresh_token=%s&client_id=cdse-public", refreshToken)
	// 发起请求
	content, e := global.SendRequest(global.AuthEndpoint, http.MethodPost, global.UrlEncoded, []byte(bodyString))
	if e != nil {
		sclog.ErrorLine("刷新Token出错！")
		return nil, e
	}
	// 反序列化响应
	// 解析响应
	var result model.LoginToken
	e = json.Unmarshal(content, &result)
	if e != nil {
		sclog.ErrorLine("反序列化响应失败！")
		return nil, e
	}
	if result.AccessToken == "" || result.RefreshToken == "" {
		sclog.ErrorLine(string(content))
		return nil, errors.New("刷新失败！")
	}
	return &result, nil
}